package org.bee.id;

/**
 * 雪花算法id生成工具
 */
public class SnowFlakeIdUtils {

    // 起始时间戳（2024-06-06 00:00:00）
    private static final long TW_EPOCH = 1717603200000L;

    // 工作机器ID位数 5
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID位数 5
    private static final long DATA_CENTER_ID_BITS = 5L;

    // 序列号位数 12
    private static final long SEQUENCE_BITS = 12L;

    // 工作机器ID左移位数 12
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 数据中心ID左移位数 17
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 时间戳左移位数 22
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

    // 序列号掩码，用于限定序列号的范围 (0-4095)
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
    // 工作机器ID（0-1023）
    private final long workerId;
    // 数据中心ID（0-31）
    private final long dataCenterId;
    // 当前时间戳
    private long lastTimestamp = -1L;
    // 序列号
    private long sequence = 0L;

    public SnowFlakeIdUtils(long workerId, long dataCenterId) {
        if (workerId > ~(-1L << WORKER_ID_BITS) || workerId < 0) {
            throw new IllegalArgumentException(String.format("机器id不能大于 %d 或小于 0", ~(-1L << WORKER_ID_BITS)));
        }
        if (dataCenterId > ~(-1L << DATA_CENTER_ID_BITS) || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("数据中心id不能大于 %d 或小于 0", ~(-1L << DATA_CENTER_ID_BITS)));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 生成下一个ID
     * @return 下一个ID
     */
    public synchronized long nextId() {
        long currentTimestamp = currentTimeMillis();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，抛出异常
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("时钟偏移了 %d 秒", lastTimestamp - currentTimestamp));
        }

        // 如果是同一时间生成的，则进行序列号自增
        if (lastTimestamp == currentTimestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            // 序列号溢出
            if (sequence == SEQUENCE_MASK) {
                // 阻塞到下一个毫秒，获得新的时间戳
                currentTimestamp = waitUntilNextMillis(currentTimestamp);
            }
        } else {
            // 时间戳改变，序列号重置
            sequence = 0L;
        }

        // 上次生成ID的时间戳
        lastTimestamp = currentTimestamp;
        return ((currentTimestamp - TW_EPOCH) << TIMESTAMP_LEFT_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    /**
     * 获取当前时间戳
     * @return 当前时间戳
     */
    protected long currentTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间戳
     * @return 当前时间戳
     */
    protected long waitUntilNextMillis(long lastTimestamp) {
        long timestamp = currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTimeMillis();
        }
        return timestamp;
    }
}
